package com.wyj.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class NettyChatClient {
    private String host;
    private int port;

    public NettyChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() {
        NioEventLoopGroup nioEventLoopGroup = null;
        try {
            //    1、创建客户端线程组
            nioEventLoopGroup = new NioEventLoopGroup();
            //    2、创建客户端启动助手
            Bootstrap bootstrap = new Bootstrap();
            //    3、设置线程组
            bootstrap.group(nioEventLoopGroup)
                    //    4、设置客户端通道实现为nio
                    .channel(NioSocketChannel.class)
                    //    5、创建一个通道初始化对象
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //    6、向pipeline中注册业务处理handler
                            socketChannel.pipeline().addLast(new StringEncoder());
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new NettyChatClientHandler());

                        }
                    });
            //    7、启动客户端并连接服务端，同时将异步改为同步
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            Channel channel = channelFuture.channel();
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()) {
                String s = scanner.nextLine();
                channel.writeAndFlush(s);
            }
            //    8、关闭通道和关闭连接池
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != nioEventLoopGroup) {
                nioEventLoopGroup.shutdownGracefully();
            }
        }
    }

    public static void main(String[] args) {
        new NettyChatClient("127.0.0.1", 19999).run();
    }
}
